﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
using McTools.Xrm.Connection;
using Microsoft.Xrm.Sdk;
using SolutionImport;
using Tanguy.WinForm.Utilities.DelegatesHelpers;

namespace RibbonBrowser
{
    public partial class MainForm : Form
    {
        #region Variables

        ConnectionManager cManager;

        SolutionManager sManager;

        CrmConnectionStatusBar ccsb;

        IOrganizationService service;

        #endregion

        #region Constructor

        public MainForm()
        {
            InitializeComponent();

            this.Text += " (v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + ")"; 
            
            this.cManager = new ConnectionManager(this);
            this.cManager.ConnectionSucceed += new ConnectionManager.ConnectionSucceedEventHandler(cManager_ConnectionSucceed);
            this.cManager.ConnectionFailed += new ConnectionManager.ConnectionFailedEventHandler(cManager_ConnectionFailed);
            this.cManager.StepChanged += new ConnectionManager.StepChangedEventHandler(cManager_StepChanged);

            ccsb = new CrmConnectionStatusBar(this.cManager);
            this.Controls.Add(ccsb);

            this.gbImportSolution.AllowDrop = true;

            ToolTip tip = new ToolTip();
            tip.SetToolTip(this.chkOverwriteUnmanagedCustomizations, "Sets whether any unmanaged customizations that have been applied over existing managed solution components should be overwritten.");
            tip.SetToolTip(this.chkConvertToManaged, "Direct the system to convert any matching unmanaged customizations into your managed solution.");
            tip.SetToolTip(this.chkActivate, "Sets whether any processes (workflows) included in the solution should be activated after they are imported.");
        }

        #endregion

        #region Connections Methods

        void cManager_StepChanged(object sender, StepChangedEventArgs e)
        {
            this.ccsb.SetMessage(e.CurrentStep);
        }

        void cManager_ConnectionFailed(object sender, ConnectionFailedEventArgs e)
        {
            this.ccsb.SetMessage(e.FailureReason);
            MessageBox.Show(e.FailureReason, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        void cManager_ConnectionSucceed(object sender, ConnectionSucceedEventArgs e)
        {
            this.service = e.OrganizationService;
            this.ccsb.SetConnectionStatus(true, e.ConnectionDetail);


            this.sManager = new SolutionManager(this.service);

            if (e.Parameter != null)
            {
                CommonDelegates.SetCursor(this, Cursors.WaitCursor);
                this.ImportArchive((ImportSettings) e.Parameter);
            }
        }

        #endregion

        private void gbImportSolution_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

                if (files.Length > 1 || !files[0].EndsWith(".zip"))
                    e.Effect = DragDropEffects.None;
                else
                    e.Effect = DragDropEffects.All;
            }
            else
                e.Effect = DragDropEffects.None;
        }

        private void gbImportSolution_DragDrop(object sender, DragEventArgs e)
        {
            ImportSettings iSettings = new ImportSettings()
            {
                DownloadLog = this.chkDownload.Checked,
                IsFolder = false,
                Path = ((string[])e.Data.GetData(DataFormats.FileDrop))[0],
                Publish = this.chkPublish.Checked,
                Activate = this.chkActivate.Checked,
                ConvertToManaged = this.chkConvertToManaged.Checked,
                OverwriteUnmanagedCustomizations = this.chkOverwriteUnmanagedCustomizations.Checked
            };

            if (this.service == null)
            {
                this.cManager.AskForConnection(iSettings);
            }
            else
            {
                this.ImportArchive(iSettings);
            }
        }

        private void ImportArchive(ImportSettings iSettings)
        {
            CommonDelegates.SetCursor(this, Cursors.WaitCursor);
            this.ccsb.SetMessage("Importing solution...");
            EnableControls(false);

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            worker.RunWorkerAsync(iSettings);
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            ImportSettings settings = (ImportSettings)e.Argument;

            if (settings.IsFolder)
            {
                this.sManager.ImportSolutionFolder(settings);
            }
            else
            {
                this.sManager.ImportSolutionArchive(settings.Path, settings);
            }

            if (((ImportSettings)e.Argument).Publish)
            {
                this.ccsb.SetMessage("Publishing solution...");
                this.sManager.PublishAll();
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                this.ccsb.SetMessage("Done!");
            }
            else
            {
                ErrorForm eForm = new ErrorForm(e.Error.Message);
                eForm.ShowDialog();
            }

            EnableControls(true);
            this.ccsb.SetMessage("");
            CommonDelegates.SetCursor(this, Cursors.Default);
        }

        private void btnBrowseFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbDialog = new FolderBrowserDialog()
            {
                Description = "Select a folder containing the three files of a solution.\r\nThe folder must be name like a solution archive (ie. MySolution_1_0_0_0)",
                ShowNewFolderButton = true
            };

            if (fbDialog.ShowDialog() == DialogResult.OK)
            {
                this.txtFolderPath.Text = fbDialog.SelectedPath;
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            ImportSettings iSettings = new ImportSettings()
            {
                DownloadLog = this.chkDownload.Checked,
                IsFolder = true,
                Path = this.txtFolderPath.Text,
                Publish = this.chkPublish.Checked,
                Activate = this.chkActivate.Checked,
                ConvertToManaged = this.chkConvertToManaged.Checked,
                OverwriteUnmanagedCustomizations = this.chkOverwriteUnmanagedCustomizations.Checked
            };

            if (this.service == null)
            {
                this.cManager.AskForConnection(iSettings);
            }
            else
            {
                this.ImportArchive(iSettings);
            }
        }

        private void EnableControls(bool enable)
        {
            MethodInvoker mi = delegate
            {
                this.chkDownload.Enabled = enable;
                this.chkPublish.Enabled = enable;
                this.chkActivate.Enabled = enable;
                this.chkConvertToManaged.Enabled = enable;
                this.chkOverwriteUnmanagedCustomizations.Enabled = enable;
                this.gbImportByFolder.Enabled = enable;
                this.gbImportSolution.Enabled = enable;
            };

            if (this.InvokeRequired)
            {
                this.Invoke(mi);
            }
            else
            {
                mi();
            }
        }

        private void tsbRate_Click(object sender, EventArgs e)
        {
            Process.Start("http://solutionimport.codeplex.com/releases");
        }

        private void tsbDiscuss_Click(object sender, EventArgs e)
        {
            Process.Start("http://solutionimport.codeplex.com/discussions");
        }

        private void tsbReportBug_Click(object sender, EventArgs e)
        {
            Process.Start("http://solutionimport.codeplex.com/WorkItem/Create");
        }

        private void tsbAbout_Click(object sender, EventArgs e)
        {
            // Displays about form
            AboutForm form = new AboutForm();
            form.StartPosition = FormStartPosition.CenterParent;
            form.ShowDialog();
        }

        private void tsbDonate_Click(object sender, EventArgs e)
        {
            string url = "";

            string business = "tanguy92@hotmail.com";  // your paypal email
            string description = "Donation%20for%20MSCRM%20Tools";            // '%20' represents a space. remember HTML!
            string country = "FR";                  // AU, US, etc.
            string currency = "EUR";                 // AUD, USD, etc.

            url += "https://www.paypal.com/cgi-bin/webscr" +
                "?cmd=" + "_donations" +
                "&business=" + business +
                "&lc=" + country +
                "&item_name=" + description +
                "&currency_code=" + currency +
                "&bn=" + "PP%2dDonationsBF";

            System.Diagnostics.Process.Start(url);
        }
    }
}
